<template>
	<div>
		<el-dialog
			:title="title"
			:visible.sync="visible"
			append-to-body
			width="70%"
			:before-close="dialogBeforeClose"
			:close-on-click-modal="false"
			@closed="handlerCancel"
		>
			<el-form
				ref="form"
				:model="formData"
				:rules="rules"
				label-width="150px"
				:inline="true"
				size="normal"
			>
				<div id="form_height">
					<el-row>
						<el-col :span="12">
							<el-form-item v-if="parentOrgName" label="父级机构">
								<el-input v-model="parentOrgName" disabled />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item
								v-if="parentOrgName && orgDialogTypeS != 2"
								label="机关类别"
							>
								<el-select
									v-model="formData.officeType"
									placeholder="请选择"
									@change="bclxChange"
								>
									<el-option
										v-for="item in curSelect == '0' ? officeType : officeTypeS"
										:key="item.value"
										:label="item.label"
										:value="item.value"
									/>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row>
						<el-col :span="12">
							<el-form-item label="机构代码" prop="orgCode">
								<label slot="label">{{ labelTitle }}代码</label>
								<el-input v-model="formData.orgCode" clearable />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="机构名称" prop="orgName">
								<label slot="label">{{ labelTitle }}名称</label>
								<el-input v-model="formData.orgName" clearable />
							</el-form-item>
						</el-col>
					</el-row>
					<!-- 医院 -->
					<div v-if="isOffice">
						<el-row>
							<el-col :span="12">
								<el-form-item label="收款账号" prop="accountReceivable">
									<el-input v-model="formData.accountReceivable" clearable />
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="机构级别">
									<el-select
										v-model="formData.orgLevel"
										placeholder="请选择"
										clearable
									>
										<el-option
											v-for="item in orgLevel"
											:key="item.value"
											:label="item.display"
											:value="item.value"
										/>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="12">
								<el-form-item label="机构等次">
									<el-select
										v-model="formData.orgOrder"
										placeholder="请选择"
										clearable
									>
										<el-option
											v-for="item in orgOrder"
											:key="item.value"
											:label="item.display"
											:value="item.value"
										/>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="所有制形式">
									<el-select
										v-model="formData.ownerShip"
										placeholder="请选择"
										clearable
									>
										<el-option
											v-for="item in ownerShip"
											:key="item.value"
											:label="item.display"
											:value="item.value"
										/>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="12">
								<el-form-item label="机构类别">
									<el-select
										v-model="formData.orgType"
										placeholder="请选择"
										clearable
									>
										<el-option
											v-for="item in orgType"
											:key="item.value"
											:label="item.display"
											:value="item.value"
										/>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="医院图标">
									<el-upload
										class="avatar-uploader"
										:action="uploadFileUrl"
										:show-file-list="false"
										:data="paramsData"
										:on-success="handleSuccess"
										:before-upload="beforeUploadPicture"
										:headers="headers"
									>
										<img v-if="imageUrl" :src="imageUrl" class="avatar" />
										<i v-else class="el-icon-plus avatar-uploader-icon"></i>
									</el-upload>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="12">
								<el-form-item label="互联网资质">
									<el-select
										v-model="formData.isInternetHospitalFlag"
										placeholder="请选择"
										clearable
									>
										<el-option
											v-for="item in whetherEnableOptions"
											:key="item.value"
											:label="item.label"
											:value="item.value"
										/>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item
									v-if="formData.isInternetHospitalFlag == '0'"
									label="互联网医院牌照号"
								>
									<el-input v-model="formData.internetHospitalCode" clearable />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="12">
								<el-form-item label="医院简介">
									<el-select
										v-model="formData.orgArticleInformationId"
										placeholder="请选择"
										clearable
									>
										<el-option
											v-for="item in orgArticleInformationIdList"
											:key="item.id"
											:label="item.title"
											:value="item.id"
										/>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="医院详细地址">
									<el-input v-model="formData.orgAddress" clearable />
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="12">
								<el-form-item label="经度">
									<el-input v-model="formData.lng" clearable />
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="纬度">
									<el-input v-model="formData.lat" clearable />
								</el-form-item>
							</el-col>
						</el-row>
					</div>
					<!-- ----------- -->
					<!-- 科室 -->
					<div v-if="isShow">
						<el-row>
							<el-col :span="12">
								<el-form-item label="科室类别">
									<el-select
										v-model="formData.deptType"
										placeholder="请选择"
										clearable
									>
										<el-option
											v-for="item in deptType"
											:key="item.value"
											:label="item.label"
											:value="item.value"
										/>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="是否为ICU科室">
									<el-select
										v-model="formData.isIcuFlag"
										placeholder="请选择"
										clearable
									>
										<el-option
											v-for="item in isIcuFlag"
											:key="item.value"
											:label="item.label"
											:value="item.value"
										/>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row>
							<el-col :span="12">
								<el-form-item label="科室所属类型">
									<el-select
										v-model="formData.deptBelongingType"
										placeholder="请选择"
										clearable
									>
										<el-option
											v-for="item in deptBelongingType"
											:key="item.value"
											:label="item.display"
											:value="item.value"
										/>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="12">
								<el-form-item label="是否特色科室">
									<el-select
										v-model="formData.isCharacteristicDeptFlag"
										placeholder="请选择"
										clearable
									>
										<el-option
											v-for="item in whetherEnableOptions"
											:key="item.value"
											:label="item.label"
											:value="item.value"
										/>
									</el-select>
								</el-form-item>
							</el-col>
						</el-row>
						<!-- ----------------------------------------------------- -->
					</div>
					<el-row>
						<el-col :span="12">
							<el-form-item label="是否启用" prop="whetherEnable">
								<el-select
									v-model="formData.whetherEnable"
									placeholder="请选择"
									clearable
								>
									<el-option
										v-for="item in whetherEnableOptions"
										:key="item.value"
										:label="item.label"
										:value="item.value"
									/>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col v-if="isShow" :span="12">
							<el-form-item label="是否可挂号" prop="isRegister">
								<el-select
									v-model="formData.isRegister"
									placeholder="请选择"
									clearable
								>
									<el-option
										v-for="item in registrationData"
										:key="item.value"
										:label="item.label"
										:value="item.value"
									/>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="备注" prop="remark">
								<el-input v-model="formData.remark" type="textarea" clearable />
							</el-form-item>
						</el-col>
					</el-row>
				</div>
				<el-form-item>
					<el-button type="primary" size="medium" @click="onSubmit">
						确定
					</el-button>
					<el-button size="medium" @click="handlerCancel"> 取消 </el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
	</div>
</template>

<script>
import { getList, codeCheck } from '@/http/org'
import { getArticleList } from '@/http/article'
import { fileURLConfig, delImageUpload } from '@/http/upLoad'
export default {
	props: {
		orgData: {
			type: Object,
			default: () => {
				return {}
			},
		},
		orgSelect: {
			type: Object,
			default: () => {
				return {}
			},
		},
		parentOrg: {
			type: Object,
			default: () => {
				return {}
			},
		},
		visible: {
			type: Boolean,
			default: false,
		},
		title: {
			type: String,
			default: '',
		},
		orgDialogType: {
			type: String,
			default: '',
		},
		curSelect: {
			type: String,
			default: '',
		},
		rowRepetition: {
			type: String,
			default: '',
		},
	},
	data() {
		var spCodeValidator = this.spCodeFun
		var spCodeValidatorS = this.spCodeFunS
		return {
			orgIcon: '',
			relativeFolderImageUrl: '',
			imageUrl: '',
			uploadFileUrl: fileURLConfig.uploadPicture,
			paramsData: {
				folderName: fileURLConfig.uploadHospitalFolderName,
			},
			orgArticleInformationIdList: [],
			labelTitle: '卫健委',
			value: 3,
			isShow: false,
			isOffice: false,
			rules: {
				orgName: [{ required: true, message: '请输入名称', trigger: 'blur' }],
				orgCode: [
					{ required: true, message: '请输入代码', trigger: 'blur' },
					{ validator: spCodeValidator, trigger: 'blur' },
				],
				primaryOrgCode: [
					{ required: true, message: '请输入原代码', trigger: 'blur' },
					{ validator: spCodeValidatorS, trigger: 'blur' },
				],
				primaryOrgName: [
					{ required: true, message: '请输入原名称', trigger: 'blur' },
				],
				whetherEnable: [
					{ required: true, message: '请选择是否启用', trigger: 'blur' },
				],
				isRegister: [
					{ required: true, message: '请选择是否可挂号', trigger: 'blur' },
				],
				accountReceivable: [
					{ required: true, message: '请输入', trigger: 'blur' },
				],
				platformDeptCode: [
					{ required: true, message: '请输入平台科室代码', trigger: 'blur' },
				],
				platformDeptName: [
					{ required: true, message: '请输入平台科室名称', trigger: 'blur' },
				],
			},
			whetherEnableOptions: [
				{
					value: '1',
					label: '否',
				},
				{
					value: '0',
					label: '是',
				},
			],
			isIcuFlag: [
				{
					value: '1',
					label: '否',
				},
				{
					value: '0',
					label: '是',
				},
			],
			//是否可挂号
			registrationData: [
				{
					value: '1',
					label: '否',
				},
				{
					value: '0',
					label: '是',
				},
			],
			deptBelongingType: [],
			officeType: [
				{ value: '0', label: '卫健委' },
				{ value: '1', label: '医院' },
			],
			officeTypeS: [{ value: 2, label: '科室' }],
			orgLevel: [],
			ownerShip: [],
			orgOrder: [],
			orgType: [],
			deptType: [
				{ value: '1', label: '急诊科室' },
				{ value: '2', label: '门诊科室' },
				{ value: '3', label: '住院科室' },
			],
		}
	},
	computed: {
		formData() {
			return this.orgData
		},
		parentOrgName() {
			return this.parentOrg ? this.parentOrg.orgName : false
		},
		orgDialogTypeS() {
			return this.orgDialogType
		},
		curSelectS() {
			return this.curSelect
		},
		headers() {
			let token = JSON.parse(window.localStorage.getItem('userMsg')).token
			return {
				Authorization: token,
			}
		},
	},
	watch: {
		formData() {
			if (this.formData.officeType == 0) {
				this.labelTitle = '卫健委'
				this.isOffice = false
				this.isShow = false
			} else if (this.formData.officeType == 1) {
				this.labelTitle = '医院'
				this.isOffice = true
				this.isShow = false
				this.imageUrl = this.formData.orgIcon
				this.orgArticleInformationIdList = this.getArticleList()
			} else if (this.formData.officeType == 2) {
				this.labelTitle = '科室'
				this.isOffice = false
				this.isShow = true
				this.imageUrl = this.formData.orgIcon
			}
		},
		curSelectS() {
			if (this.curSelect == '-1') {
				this.isOffice = false
				this.isShow = true
				this.labelTitle = '科室'
			}
		},
	},
	created() {
		/**
		 * ORG_OWNERSHIP_DICT:所有制形式
		 * ORG_LEVEL_DICT:机构级别
		 * 机构等次
		 * ORG_CLASS_DICT:机构类别
		 * 科室类别
		 */
		getList({ type: 'ORG_OWNERSHIP_DICT' }).then(({ data }) => {
			this.ownerShip = data.data
		})
		getList({ type: 'ORG_LEVEL_DICT' }).then(({ data }) => {
			this.orgLevel = data.data
		})
		getList({ type: 'ORG_CLASS_DICT' }).then(({ data }) => {
			this.orgType = data.data
		})
		getList({ type: 'ORG_ORDER_DICT' }).then(({ data }) => {
			this.orgOrder = data.data
		})
		getList({ type: 'RC_DEPT_DICT' }).then(({ data }) => {
			this.deptBelongingType = data.data
		})
	},
	methods: {
		getArticleList() {
			getArticleList({ articleType: '2', publish: '0', delFlag: '0' }).then(
				({ data }) => {
					this.orgArticleInformationIdList = data.data
				},
			)
		},
		// 文件上传前置方法
		beforeUploadPicture(file) {
			const isImage =
				file.type === 'image/png' ||
				file.type === 'image/jpg' ||
				file.type === 'image/jpeg'
			// file.type === 'image/bmp' ||
			// file.type === 'image/gif' ||
			// file.type === 'image/webp'
			const isLt2M = file.size < 1024 * 1024 * 2
			if (!isImage) {
				this.$message.error('上传只能是png,jpg格式!')
			}
			if (!isLt2M) {
				this.$message.error('上传图片大小不能超过 2MB!')
			}
			return isImage && isLt2M
		},
		handleSuccess(res, file) {
			this.imageUrl = URL.createObjectURL(file.raw)
			if (file.response.head.code == '200') {
				this.orgIcon = file.response.data[0].httpImageUrl
			}
			if (this.relativeFolderImageUrl) {
				delImageUpload({
					imagePath: this.relativeFolderImageUrl,
				}).then(({ data }) => {
					if (data.head.code == '200') {
						this.relativeFolderImageUrl =
							file.response.data[0].relativeFolderImageUrl
					}
				})
			} else {
				this.relativeFolderImageUrl =
					file.response.data[0].relativeFolderImageUrl
			}
		},
		deleteEmptyProperty(obj) {
			var object = obj
			for (var i in object) {
				var value = object[i]
				if (typeof value === 'object') {
					if (Array.isArray(value)) {
						if (value.length == 0) {
							delete object[i]
							continue
						}
					}
					this.deleteEmptyProperty(value)
				} else {
					if (value === '' || value === null || value === undefined) {
						delete object[i]
					}
				}
			}
			return object
		},
		bclxChange() {
			if (this.formData.officeType == 0) {
				this.labelTitle = '卫健委'
				this.formData.orgCode = ''
				this.formData.orgCode = ''
				this.isOffice = false
				this.isShow = false
				this.deleteEmptyProperty(this.formData)
				this.$nextTick(() => {
					this.$refs['form'].clearValidate()
				})
			}
			if (this.formData.officeType == 1) {
				this.labelTitle = '医院'
				this.formData.orgCode = ''
				this.formData.orgCode = ''
				this.isOffice = true
				this.isShow = false
				this.deleteEmptyProperty(this.formData)
				this.$nextTick(() => {
					this.$refs['form'].clearValidate()
				})
			}
			if (this.formData.officeType == 2) {
				this.formData.orgCode = ''
				this.formData.orgCode = ''
				this.isOffice = false
				this.isShow = true
				this.deleteEmptyProperty(this.formData)
				this.$nextTick(() => {
					this.$refs['form'].clearValidate()
				})
			}
		},
		dialogBeforeClose() {
			this.$emit('update:visible', false)
			if (this.parentOrg) {
				this.$emit('update:parentOrg', {})
			}
			this.$emit('update:orgData', {
				orgName: '',
				remark: '',
			})
			this.handlerResetFields()
		},
		onSubmit() {
			this.$refs.form.validate(valid => {
				if (valid) {
					this.imageUrl = ''
					this.relativeFolderImageUrl = ''
					this.formData.orgIcon = this.orgIcon
					console.log(this.formData, '1213123213213')
					this.$emit(
						'submit',
						this.formData,
						{ ...this.parentOrg },
						this.orgDialogType,
					)
				} else {
					return false
				}
			})
		},
		handlerCancel() {
			this.labelTitle = ''
			if (this.orgIcon) {
				delImageUpload({
					imagePath: this.relativeFolderImageUrl,
				}).then(({ data }) => {
					if (data.head.code == '200') {
						this.imageUrl = ''
						this.relativeFolderImageUrl = ''
					}
				})
			}
			this.handlerResetFields()
			this.dialogBeforeClose()
		},
		handlerResetFields() {
			this.$nextTick(() => {
				this.$refs['form'].clearValidate()
			})
		},
		// 机构代码唯一性校验
		spCodeFun(rule, value, callback) {
			codeCheck({
				id: this.rowRepetition,
				orgCode: value,
				parentUuid: this.formData.parentUuid,
			})
				.then(({ data }) => {
					if (data.head.code == 200) {
						callback()
					}
				})
				.catch(({ data }) => {
					if (data.head.code == 400) {
						callback(new Error('机构代码不能重复'))
						return
					} else {
						callback()
					}
				})
		},
		spCodeFunS(rule, value, callback) {
			codeCheck({ id: this.rowRepetition, primaryOrgCode: value })
				.then(({ data }) => {
					if (data.head.code == 200) {
						callback()
					}
				})
				.catch(({ data }) => {
					if (data.head.code == 400) {
						callback(new Error('原机构代码不能重复'))
						return
					} else {
						callback()
					}
				})
		},
	},
}
</script>

<style lang="scss" scoped>
#form_height {
	overflow: auto;
}
.avatar-uploader .el-upload {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
}
.avatar-uploader .el-upload:hover {
	border-color: #409eff;
}
.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 100px;
	height: 100px;
	line-height: 100px;
	text-align: center;
}
.avatar {
	width: 100px;
	height: 100px;
	display: block;
}
</style>
